from django.shortcuts import render
import pickle, base64

from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

# Create your views here.
# 购物车功能在用户登陆或者没有登陆的情况下均可以访问
# 请求方式　　post /cart/
# 前段传入的数据为sku_id count selected(非必须)
# 流程(如果用户没有登陆，则相关的数据存储在cookie中，如果用户已经
# 登陆,那么将数据存在redis数据库中，)
# 在cookie中的数据格式为{"sku_id2":{"count": 2, "selected":True,}，
# 　　　　　　　　　　　　　"sku_id3":{"count": 5, "selected":True,}}
# 在redis中的数据存储的格式为f分为两种格式
# 格式1(set):用于存储用户是不是已经勾选相应的商品　例如:cart1_user [sku_id1, sku_id2, sku_id3...]
# 格式2(hash)：用于存储用户商品的id和数量　例如: cart2_user {"sku_id1": num1, "sku_id2": num2,.. }
from carts import constants
from carts.serializers import CartSerializer, CartSKUSerializer, CartDeleteSerializer, CartSelectAllSerializer
from goods.models import SKU


class CartView(APIView):
    """购物车视图"""

    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        还是继续校验了，但是校验失败的时候不会处理
        这里，我们只是希望不报错而已，要登陆的用户还是通过request.user来获取的
        """
        pass

    def post(self, request):
        """添加商品至购物车"""
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')
        # 判断用户是否已经登陆了
        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None
            # user.is_authenticated 为True，表示当前访问者有登陆权限,如果登陆了，则把用户提交的商品信息保存到redis中
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            pl = redis_conn.pipeline()
            # 保存购物车商品sku_id和数量到hash数据中
            pl.hincrby("cart_%s" % user.id, sku_id, count)
            # 保存购物车商品勾选状态到set集合中,集合中至保存selected=True的商品
            pl.sadd("cart_selected_%s" % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            # 如果用户没有登陆，保存数据至cookie中,　返回的数据中应该包含cookie
            # 1. 获取 request.COOKIE 中的购物车数据
            cart = request.COOKIES.get('cart')
            # 判断以前是否有添加商品到cookie购物车中
            if cart is None:
                # 如果没有，则默认就是空字典
                cart = {}
            else:
                # 如果有，则把字符串还原成字典
                print(cart, type(cart))
                cart = pickle.loads(base64.b64decode(cart))

            # 获取购物车指定当前sku_id的信息,结果为字典
            # 如果cookie中的存在新增的商品，只需要将其数量增加count
            sku_dict = cart.get(sku_id)
            if sku_dict:
                count += int(sku_dict["count"])
                # count += sku_dict["count"]
            cart[sku_id] = {
                "count": count,
                "selected": selected,
            }
            # 使用pickle和base64把字典转换成字符串
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            # 响应前端附带cookie
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            response.set_cookie("cart", cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def get(self, request):
        """获取购物车中的商品列表"""
        # 判断是否登陆，选择从redis还是从cookie中提取数据
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        # 从购物车获取商品sku_id、数量以及勾选状态
        if user is not None and user.is_authenticated:
            # 从redis中获取购物车
            # 用户已登录，从redis中读取
            redis_conn = get_redis_connection('cart')
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)
            redis_cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)
            """
            redis中数据是分散存储的，我们可以重新组装数据格式与cookie中的购物车数据保持一次，
            这样的话，就可以在返回数据时，两者共用一段代码
            １　cookie保存数据的格式　cart
            {
              sku_id1: {"count": 2, "selected":True,}
              sku_id2: {"count": 1, "selected":True,}
            }
            ２　redis保存数据的格式为hash  cart_user {"sku_id1": num1, "sku_id2": num2,.. }
                      set   cart_selected_user [sku_id1, sku_id2, sku_id3...]
            """
            cart = {}
            for sku_id, count in redis_cart.items():
                cart[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in redis_cart_selected
                }
        else:
            # 获取 request.COOKIE 中的购物车数据
            cart = request.COOKIES.get('cart')
            # 判断以前是否有添加商品到cookie购物车中
            if cart is None:
                # 如果没有，则默认就是空字典
                cart = {}
            else:
                # 如果有，则把字符串还原成字典
                cart = pickle.loads(base64.b64decode(cart))

        print(cart)  # 以上代码保证两种存储方法，返回的数据cart格式一致
        # 遍历购物车，从数据库中提取前端需要的其他字段
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]['count']
            sku.selected = cart[sku.id]["selected"]

        serializer = CartSKUSerializer(instance=skus, many=True)
        # 注意instance为模型的数据，data为字典形式的数据

        return Response(serializer.data)

    def put(self, request):
        """更新购物城中的商品信息"""
        # 调用序列化器校验数据
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')
        print("1")
        # 判断用户是否已经登陆了
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None
        print("2")
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection("cart")
            pl = redis_conn.pipeline()
            # 保存购物车商品sku_id和数量到hash数据中
            pl.hset("cart_%s" % user.id, sku_id, count)
            # 保存购物车商品勾选状态到set集合中
            # 在更新的时候并不是每次状态都是勾选的，所以要判断一下。
            if selected:
                # select = True，则sadd表示添加一个成员，有去重功能
                pl.sadd("cart_selected_%s" % user.id, sku_id)
            else:
                # select = False，则srem表示移除一个成员
                pl.srem("cart_selected_%s" % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            print("3")
            # 从cookie中获取购物车
            # 1. 获取 request.COOKIE 中的购物车数据
            cart = request.COOKIES.get('cart')
            # 判断以前是否有添加商品到cookie购物车中
            if cart is None:
                # 如果没有，则默认就是空字典
                cart = {}
            else:
                # 如果有，则把字符串还原成字典
                print(11111, type(cart))
                cart = pickle.loads(base64.b64decode(cart))

            cart[sku_id] = {
                'count': count,
                'selected': selected
            }

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response

    def delete(self, request):
        """删除购物车中指定的商品"""
        serializer = CartDeleteSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']

        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，在redis中删除
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 从购物车删除对应的hash成员 hdel
            pl.hdel("cart_%s" % user.id, sku_id)
            # 从勾选状态中删除对饮的set成员
            pl.srem("cart_selected_%s" % user.id, sku_id)
            pl.execute()
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            response = Response(serializer.data)

            # 用户未登录，在cookie中删除
            cart = request.COOKIES.get('cart')
            # print(cart)
            if cart is not None:
                # cart = pickle.loads(base64.b64decode(cart.encode()))均可
                cart = pickle.loads(base64.b64decode(cart))
                if sku_id in cart: #仅仅获取的是键
                    del cart[sku_id]

                    cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                    response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
        return response


# 购物车全选的逻辑
class CartSelectAllView(APIView):
    """
    购物车全选
    """

    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass

    def put(self, request):
        serializer = CartSelectAllSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        selected = serializer.validated_data['selected']

        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录，在redis中保存
            redis_conn = get_redis_connection('cart')
            cart = redis_conn.hgetall('cart_%s' % user.id)
            sku_id_list = cart.keys()

            if selected:
                # 全选
                redis_conn.sadd('cart_selected_%s' % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_conn.srem('cart_selected_%s' % user.id, *sku_id_list)
            return Response({'message': 'OK'})
        else:
            # cookie  cart为string类型
            cart = request.COOKIES.get('cart')
            response = Response({'message': 'OK'})

            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                # 设置购物车的cookie
                # 需要设置有效期，否则是临时cookie
                response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)

            return response
